package com.weacar.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.ToolsUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 修改个人信息
 */

public class ChangePersonInfoActivity extends BaseActivity {

    @BindView(R.id.cl_change_password)
    ConstraintLayout cl_change_password;
    @BindView(R.id.cl_nickname)
    ConstraintLayout cl_nickname;
    @BindView(R.id.et_old_pwd)
    EditText et_old_pwd;
    @BindView(R.id.et_new_pwd)
    EditText et_new_pwd;
    @BindView(R.id.et_new_pwd_again)
    EditText et_new_pwd_again;
    @BindView(R.id.et_nickname)
    EditText et_nickname;

    public LoginBean loginBean;
    public String token = "";

    @OnClick({R.id.iv_back, R.id.iv_old_password_clean, R.id.iv_new_password_clean, R.id.iv_new_password_again_clean, R.id.tv_commit, R.id.iv_back_nickname, R.id.cl_nickname, R.id.tv_commit_nickname})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
            case R.id.iv_back_nickname:
                finish();
                break;
            case R.id.iv_old_password_clean:
                et_old_pwd.setText("");
                break;
            case R.id.iv_new_password_clean:
                et_new_pwd.setText("");
                break;
            case R.id.iv_new_password_again_clean:
                et_new_pwd_again.setText("");
                break;
            case R.id.tv_commit:
                changePwd();
                break;
            case R.id.cl_nickname:
                et_nickname.setText("");
                break;
            case R.id.tv_commit_nickname:
                changeNickname();
                break;

        }
    }


    /**
     * 修改密码接口
     */
    public void changePwd() {

        if (!ToolsUtil.isPassword(et_old_pwd.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确格式的旧密码,6-8位字母和数字");
            return;
        }

        if (!ToolsUtil.isPassword(et_new_pwd.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确格式的新密码,6-8位字母和数字");
            return;
        }

        if (!et_new_pwd_again.getText().toString().trim().equals(et_new_pwd.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "2次输入的密码不一致");
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        try {
            showLoading("正在修改中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.change_pwd_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("oldpwd", et_old_pwd.getText().toString().trim());
            js_request.put("newpwd", et_new_pwd.getText().toString().trim());
            js_request.put("token", token);

            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("Login_url =  " + params.getUri());
            LogUtils.d("login_params = " + params.getBodyContent());

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtils.d("result = " + result);
                    closeLoading();
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        ToastUtil.showShort(getApplicationContext(), "密码修改成功");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 500);
                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改昵称
     */
    public void changeNickname() {

        if (et_nickname.getText().toString().trim().equals("")) {
            ToastUtil.showShort(getApplicationContext(), "昵称不能为空");
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }


        try {
            showLoading("正在修改中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.change_nickname_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("nickname", et_nickname.getText().toString().trim());
            js_request.put("token", token);

            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("Login_url =  " + params.getUri());
            LogUtils.d("login_params = " + params.getBodyContent());

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtils.d("result = " + result);
                    closeLoading();
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        ToastUtil.showShort(getApplicationContext(), "昵称修改成功");
                        // 修改成功记录到本地
                        loginBean.getMsg().setNickname(et_nickname.getText().toString().trim());
                        Constans.isRefreshPersonInfo = true;
                        SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", loginBean);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 500);
                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_change_person_info);
        ButterKnife.bind(this);
        AppManager.getInstance().addActivity(this);

        String changePassword = getIntent().getStringExtra("changePassword");
        if (changePassword != null) {
            cl_change_password.setVisibility(View.VISIBLE);
            cl_nickname.setVisibility(View.GONE);
        } else {
            cl_change_password.setVisibility(View.GONE);
            cl_nickname.setVisibility(View.VISIBLE);
        }
        initData();
    }

    public void initData() {
        loginBean = SharedPreferenceUtil.getObject(getApplicationContext(), "loginBean");
        token = loginBean.getMsg().getToken();
    }

}
